package com.javatip.project.interceptor;

import com.javatip.common.utils.HardwareInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Component
public class RegistrationCodeInterceptor implements HandlerInterceptor {

    // 获取当前路径
    String currentPath = System.getProperty("user.dir");
    // 存储注册码的位置
    String registrationCodePath = currentPath + "/src/main/resources/Validation/registrationCode.txt";

    public static volatile boolean isVerified = false;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 读取注册码
        String registrationCode = "";
        try {
            registrationCode = new String(Files.readAllBytes(Paths.get(registrationCodePath)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (HardwareInfo.validateRegistrationCode(HardwareInfo.generateApplicationCode(), registrationCode)) {
            isVerified = true;
        }

        // 排除静态资源路径
        if (requestURI.startsWith("/css/") || requestURI.startsWith("/js/") || requestURI.startsWith("/images/") || requestURI.startsWith("/static/") ||
                requestURI.startsWith("/webjars/") ||
                requestURI.equals("/swagger-ui.html") ||
                requestURI.equals("doc.html")||
                requestURI.startsWith("/swagger-resources/**") ||
                requestURI.startsWith( "/v2/**")
                || requestURI.equals("/favicon.ico")
        ) {
            return true;
        }

        HttpSession session = request.getSession(false);  // 使用 false 参数避免创建新的 session
        Boolean registrationSuccess = (session != null) ? (Boolean) session.getAttribute("registrationSuccess") : null;

        // 已验证或注册成功则继续
        if (registrationSuccess != null && registrationSuccess || isVerified) {
            if (requestURI.equals("/register")) {
                response.sendRedirect("/login");  // 重定向前不再访问 session
                return false;
            }
            return true;
        }

        // 未验证时重定向到 /register
        if (requestURI.equals("/login") || requestURI.equals("/validateApplyCode")) {
            response.sendRedirect("/register");
            return false;
        }

        return true;
    }

}
